using Manager;
using System;
using UnityEngine;

namespace Enemy
{
    public class BaseEnemy : MonoBehaviour
    {
        [SerializeField]
        protected Animator anim;
        [SerializeField]
        public GameObject indicator;
        protected Rigidbody rb;
        protected GameObject point;//敌人发射子弹的点

        [Header("属性")]
        public float MaxHp;
        public float Hp;
        public float AttackRange;//敌人的攻击数值
        public float attackCooldown = 1f; // 攻击冷却时间
        public float nextAttackTime; // 下一次允许攻击的时间
        public int experienceAmount;// 击败后可得的经验值
        [SerializeField]
        protected float delay = 0;//敌人出现时延迟攻击玩家的时间
        [SerializeField]
        private float backForce;//击退力度
        protected bool isDead = false;//是否死亡
        private bool canAction = true;

        [Header("动画状态属性")]
        protected bool isAttack;
        protected bool isDie;
        protected bool isHit;
        protected bool isMove;

        public GameObject healthBar;
        public GameObject bulletPrefab;
        private GameObject experiencePoints;//经验值物品
        private GameObject damageNumPrefab;//伤害数字
        private void Awake()
        {
            //创建血条
            healthBar = Instantiate(Resources.Load<GameObject>("Prefabs/pfHealthBarUI"));
            healthBar.transform.SetParent(GameObject.Find("Canvas").transform);
            healthBar.GetComponent<HealthBar>().followTarget = gameObject;

            anim = GetComponent<Animator>();
            indicator = transform.Find("Indicator").gameObject;
            rb = GetComponent<Rigidbody>();

        }

        protected void Start()
        {
            backForce = 1f;
            experiencePoints = Resources.Load<GameObject>("Prefabs/FallenItem/experiencePoints");
            damageNumPrefab = Resources.Load<GameObject>("Prefabs/UI/DamageNum");

            healthBar.GetComponent<HealthBar>().UpdateHp((Hp / MaxHp), Hp);
        }
  
        protected void Update()
        {
            //敌人出现时延迟攻击玩家的时间
            delay -= Time.deltaTime;
            if (delay > 0) return;
            
            if(!isDead)
                Action();

        }

        /// <summary>
        /// 对玩家做出的行为
        /// </summary>
        public virtual void Action() 
        {
            if (isDead) return;
        }

        
        public virtual void GetHit()
        {
            if(isDead) return;//如果死亡就不需要再次受伤
            bool isCriticalHit;//是否暴击
            //Hp -= Player.Player.instance.attackRange;
            float hitNum = Player.Player.instance.GetAttackRange(out isCriticalHit);
            Hp -= hitNum;
            //击退效果
            PushBack();

            //显示伤害数值(生成的位置在子弹的位置+随机偏移量)
            DamageNum damageNum = PoolManager.Release(damageNumPrefab).GetComponent<DamageNum>();
            damageNum.SetPositon(transform.position + Vector3.one * UnityEngine.Random.Range(-0.5f, 0.5f));
            damageNum.ShowUIDamage(hitNum, false, isCriticalHit);

            //播放受伤动画
            if(anim)
                anim.SetTrigger("isHit");

            healthBar.GetComponent<HealthBar>().UpdateHp((Hp / MaxHp), Hp);

            if (Hp <= 0)
            {
                isDead = true;
                Die();
            }
        }

        /// <summary>
        /// 击退效果
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void PushBack()
        {
            Vector3 dir = transform.position - Player.Player.instance.transform.position;
            dir.Normalize();
            rb.AddForce(dir * backForce, ForceMode.Impulse);
        }


        /// <summary>
        /// 敌人死亡后的处理
        /// </summary>
        public virtual void Die()
        {

            //设置layer为default,防止死亡玩家还可以检测敌人
            gameObject.layer = LayerMask.NameToLayer("Default");

            //停止当前物体身上的携程
            StopAllCoroutines();

            //给玩家增加经验值
            ExperienceManager.Instance.AddExperience(experienceAmount);

            indicator.SetActive(false);

            //一定要先掉落经验物品再减少敌人数量，否则敌人数量先减少为0，物品还没有生成，导致最后生成的物品不会向玩家移动
            //掉落经验物品
            CreateExperienceItem();

            //减少当前波敌人的数量
            GameManager.Instance.EnemyNumChanged();

            //播放敌人死亡动画
            if (anim)
            {
                anim.SetTrigger("Die");
                //获得动画的长度
                float animLength = anim.GetCurrentAnimatorStateInfo(0).length;
                Invoke("DestoryGameObject", animLength);
            }
            else
            {
                Invoke("DestoryGameObject", 1f);
            }
      
            Destroy(healthBar);
            
        }

        public void DestoryGameObject()
        {
            gameObject.SetActive(false);
        }

        public void CreateExperienceItem()
        {
            GameObject experienceItem = PoolManager.Release(experiencePoints, transform.position, Quaternion.identity);
        }


        protected void OnTriggerEnter(Collider other)
        {
            if (other.gameObject.CompareTag("Player"))
            {
                Player.Player.instance.HitPlayer(AttackRange);
            }
        }

    }
}